package com.quanyan.club.pullclub.web;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.ltsopensource.core.json.JSON;
import com.quanyan.BaseRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.constants.ClubRedisConstants;
import com.quanyan.club.mapper.PullClubMapper;
import com.quanyan.club.pullclub.entity.req.*;
import com.quanyan.club.pullclub.entity.resp.RespSellBusiness;
import com.quanyan.club.pullclub.service.PullClubOneService;
import com.quanyan.club.pullclub.service.PullClubService;
import com.quanyan.club.pullclub.service.PullClubSupportService;
import com.quanyan.club.pullclub.utils.StringUtils;
import com.quanyan.club.sms.ClubSmsService;
import com.quanyan.club.web.BaseController;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xian-guo on 2017/2/13.
 */
@RestController
@RequestMapping(value = "/api/club/pullclub/")
public class PullClubController extends BaseController {

    private static Logger logger = Logger.getLogger(PullClubController.class);

    @Autowired
    private PullClubOneService pullClubOneService;
    @Autowired
    private PullClubSupportService pullClubSupportService;
    @Autowired
    private ClubSmsService clubSmsService;
    @Autowired
    private PullClubService pullClubService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录注册
     * 64wkA2XLfsPhO/HycQUz7ay3NS8VqYJN
     * type=1&code=QC123456
     *
     * @param reqRegisterMsg
     * @return
     */
    @RequestMapping(value = "pullClubRegister", method = RequestMethod.POST)
    public APIResponse pullClubRegister(@RequestBody ReqRegisterMsg reqRegisterMsg) {
        logger.warn("---pullClubRegister----" + JSON.toJSONString(reqRegisterMsg));
        if (StringUtil.isNotBlank(reqRegisterMsg.getToken())) {
            Map<String, String> paramMap = volidateDate(reqRegisterMsg.getCode());
            String key = ClubRedisConstants.CLUB_CHANNEL_TOKEN + paramMap.get("code") + reqRegisterMsg.getToken();
            RedisKey redisKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, key);
            if (redisTemplate.exists(redisKey)) {//token未过期
                reqRegisterMsg.setIsToken((byte) 0);
                String code = (String) redisTemplate.get(redisKey);
                String type = paramMap.get("type");
                if ("2".equals(type) && code.startsWith("QC")) {
                    //获取登录信息
                    return clubRegisterMeth(reqRegisterMsg);
                } else if ("3".equals(type) && code.startsWith("FC")) {//exCode
                    //获取登录信息
                    return clubRegisterMeth(reqRegisterMsg);
                }
                return APIResponse.returnFail("登录失败，请重试");
            }
        }
        if (StringUtil.isBlankOrNull(reqRegisterMsg.getSmsCode())) {
            return APIResponse.returnFail("请重新登录");
        }
        //验证验证码
        APIResponse apiResponse = clubSmsService.checkCode(reqRegisterMsg.getSmsCode(), reqRegisterMsg.getMobile());
        if (!apiResponse.isRet() || apiResponse.getErrcode() != 200) {
            return APIResponse.returnFail("短信验证码验证失败");
        }
        //获取登录信息
        reqRegisterMsg.setIsToken((byte) 1);//token过期了
        return clubRegisterMeth(reqRegisterMsg);
    }

    /**
     * 获取登录信息
     *
     * @param reqRegisterMsg
     * @return
     */
    private APIResponse clubRegisterMeth(ReqRegisterMsg reqRegisterMsg) {
        //解密
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("type", "1");
        if (!StringUtil.isBlankOrNull(reqRegisterMsg.getSellCode())) {//不是渠道商登录
            paramMap = volidateDate(reqRegisterMsg.getSellCode());
            reqRegisterMsg.setSellCode(paramMap.get("code"));
        }
        switch (Integer.valueOf(paramMap.get("type"))) {
            case 1://1渠道商
                return pullClubOneService.channelRegister(reqRegisterMsg);
            case 2://2经销商
                return pullClubOneService.sellRegister(reqRegisterMsg);
            case 3://3普通用户，通过经销商推广码链接
                reqRegisterMsg.setType((byte) 1);
                return pullClubOneService.customerRegister(reqRegisterMsg);
            case 4://4普通用户，通过渠道商推广码链接
                reqRegisterMsg.setType((byte) 0);
                return pullClubOneService.customerRegister(reqRegisterMsg);
            case 5://老带新
                reqRegisterMsg.setType((byte) 2);
                return pullClubOneService.customerRegister(reqRegisterMsg);
            default:
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
    }

    /**
     * 用户退出
     *
     * @param channelLoginOut
     * @return
     */
    @RequestMapping(value = "userLoginOut", method = RequestMethod.POST)
    public APIResponse userLoginOut(@RequestBody @Valid ChannelLoginOut channelLoginOut) {
        Map<String, String> paramMap = volidateDate(channelLoginOut.getCode());
        logger.warn("--" + JSON.toJSONString(paramMap));
        channelLoginOut.setCode(paramMap.get("code"));
        return pullClubOneService.userLoginOut(channelLoginOut);
    }

    /**
     * 获取参数加密字符串
     */
    @RequestMapping("getEncryptCode")
    public APIResponse getEncryptCode(@RequestBody Map map) {
        Integer type = MapUtils.getInteger(map, "type");
        String code = MapUtils.getString(map, "code");
        if (type == null || StringUtil.isBlankOrNull(code)) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        return APIResponse.returnSuccess(pullClubSupportService.getEncryptCode(type, code));
    }

    /**
     * 我垃新的俱乐部列表
     */
    @RequestMapping("myPullNewClubs")
    public APIResponse queryMyPullClubs(HttpServletRequest request, @RequestBody BaseRequest base) {
        return APIResponse.returnSuccess(
                pullClubService.getPullNewClubsByUid(getUid(request, true), base.getPageNo(), base.getPageSize()));
    }

    /**
     * 进入首页
     *
     * @param reqHomePage
     * @return
     */
    @RequestMapping(value = "homePageData", method = RequestMethod.POST)
    public APIResponse homePageData(@RequestBody ReqHomePage reqHomePage) {
        logger.warn("--homePageData--" + JSON.toJSONString(reqHomePage));
        if ("QD".equals(reqHomePage.getIsChannel())) {//渠道商
            Map<String, String> exParam = volidateDate(reqHomePage.getExCode());
            Map<String, String> seParam = volidateDate(reqHomePage.getSellCode());
            reqHomePage.setExCode(exParam.get("code"));//获取明文code
            reqHomePage.setSellCode(seParam.get("code"));
        } else if ("FX".equals(reqHomePage.getIsChannel())) {
            Map<String, String> exParam = volidateDate(reqHomePage.getExCode());
            reqHomePage.setExCode(exParam.get("code"));//获取明文code
        } else {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        return pullClubOneService.homePageData(reqHomePage);
    }

    /**
     * 获取二维码
     *
     * @param qrCodeReq
     * @return
     */
    @RequestMapping(value = "getZxingCode", method = RequestMethod.POST)
    public APIResponse getZxingCode(@RequestBody QrCodeReq qrCodeReq) {
        if (StringUtils.isBlankOrNull(qrCodeReq.getChannel())){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        if ("QD".equals(qrCodeReq.getChannel())){
            if (StringUtils.isNotBlankOrNull(qrCodeReq.getSellCode())){
                Map<String, String> stringMap=volidateDate(qrCodeReq.getSellCode());
                qrCodeReq.setDESsellCode(qrCodeReq.getSellCode());//加密的
                qrCodeReq.setSellCode(stringMap.get("code"));//解密的
                return pullClubOneService.getZxingCode(qrCodeReq);
            }
            if (StringUtils.isNotBlankOrNull(qrCodeReq.getExCode())){
                Map<String, String> stringMap=volidateDate(qrCodeReq.getExCode());
                qrCodeReq.setDESexCode(qrCodeReq.getExCode());
                qrCodeReq.setExCode(stringMap.get("code"));
                return pullClubOneService.getZxingCode(qrCodeReq);
            }
        }else if ("FX".equals(qrCodeReq.getChannel())){
            if (StringUtils.isNotBlankOrNull(qrCodeReq.getExCode())){
                Map<String, String> stringMap=volidateDate(qrCodeReq.getExCode());
                qrCodeReq.setDESexCode(qrCodeReq.getExCode());
                qrCodeReq.setExCode(stringMap.get("code"));
                return pullClubOneService.getZxingCode(qrCodeReq);
            }
        }
        return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
    }

    @RequestMapping(value = "plQrCode", method = RequestMethod.POST)
    public APIResponse get(@RequestBody Map map, HttpServletRequest request){
        String url = MapUtils.getString(map, "url");
        String pam = MapUtils.getString(map, "key");
        String value = MapUtils.getString(map, "value");
        if (StringUtil.isBlankOrNull(url) || StringUtil.isBlankOrNull(pam) || StringUtil.isBlankOrNull(value)){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        return pullClubOneService.PLQrCode(getUid(request, true), url, pam, value);
    }


    @RequestMapping(value = "incomeDetails", method = RequestMethod.POST)
    public String queryIncomeDetails(@RequestBody @Valid ReqIncomeDetail reqIncomeDetail,
                                     BindingResult bindingResult) {
        reqIncomeDetail.setPageNo(reqIncomeDetail.getPageNo() + 1);
        //解密
        Map<String, String> paramMap = pullClubSupportService.getDecryptCode(reqIncomeDetail.getCode());
        if (!paramMap.containsKey("code")) {
            return JSONObject.toJSONString(
                    APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID));
        }
        logger.warn("--" + JSON.toJSONString(paramMap));
        reqIncomeDetail.setCode(paramMap.get("code"));
        APIResponse apiResponse = pullClubService.queryIncomeDetail(reqIncomeDetail);
        return JSONObject.toJSONString(apiResponse,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    @RequestMapping(value = "withdrawDetails", method = RequestMethod.POST)
    public String queryIncomeTotal(@RequestBody @Valid ReqIncomeDetail reqIncomeDetail,
                                   BindingResult bindingResult) {
        reqIncomeDetail.setPageNo(reqIncomeDetail.getPageNo() + 1);
        //解密
        Map<String, String> paramMap = pullClubSupportService.getDecryptCode(reqIncomeDetail.getCode());
        if (!paramMap.containsKey("code")) {
            return JSONObject.toJSONString(
                    APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID));
        }
        logger.warn("--" + JSON.toJSONString(paramMap));
        reqIncomeDetail.setCode(paramMap.get("code"));
        APIResponse apiResponse = pullClubService.queryIncomeTotal(reqIncomeDetail);
        return JSONObject.toJSONString(apiResponse,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    @RequestMapping(value = "bindAccount", method = RequestMethod.POST)
    public String bindAccount(@RequestBody @Valid ReqPullBind reqPullBind,
                              BindingResult bindingResult) {
        //验证验证码
        if (reqPullBind.getType() == 1) {
            APIResponse apiResponse = clubSmsService.checkCode(reqPullBind.getSmsCode(),
                    reqPullBind.getMobile());
            if (!apiResponse.isRet() || apiResponse.getErrcode() != 200) {
                return JSONObject.toJSONString(APIResponse.returnFail("短信验证码验证失败"));
            }
        }
        //解密
        Map<String, String> paramMap = pullClubSupportService.getDecryptCode(reqPullBind.getCode());
        if (!paramMap.containsKey("code")) {
            return JSONObject.toJSONString(APIResponse.returnFail(
                    ApiResponseEnum.PARAMETER_INVALID));
        }
        logger.warn("--" + JSON.toJSONString(paramMap));
        reqPullBind.setCode(paramMap.get("code"));
        return JSONObject.toJSONString(pullClubService.bindingAccount(reqPullBind),
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    @RequestMapping(value = "preWithdrawApply", method = RequestMethod.POST)
    public String preWithdrawApply(@RequestBody @Valid ReqIncomeDetail reqIncomeDetail,
                                   BindingResult bindingResult) {
        //解密
        Map<String, String> paramMap = pullClubSupportService.
                getDecryptCode(reqIncomeDetail.getCode());
        if (!paramMap.containsKey("code")) {
            return JSONObject.toJSONString(APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID));
        }
        logger.warn("--" + JSON.toJSONString(paramMap));
        reqIncomeDetail.setCode(paramMap.get("code"));
        return JSONObject.toJSONString(pullClubService.preWithdrawApply(reqIncomeDetail),
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    @RequestMapping(value = "withdrawApply", method = RequestMethod.POST)
    public APIResponse withdrawApply(@RequestBody @Valid ReqPullWithdrawApply req,
                                     BindingResult bindingResult, HttpServletRequest request) {

        //解密
        Map<String, String> paramMap = pullClubSupportService.getDecryptCode(req.getCode());
        if (!paramMap.containsKey("code")) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        logger.warn("--" + JSON.toJSONString(paramMap));
        req.setCode(paramMap.get("code"));
        String key = ClubRedisConstants.CLUB_CHANNEL_WITHDRAW + req.getCode();
        RedisKey redisKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, key);
        APIResponse response = null;
        if (redisTemplate.exists(redisKey)) {
            return APIResponse.returnFail("正在提现中...");
        } else {
            redisTemplate.set(redisKey, 1);
        }
        APIResponse apiResponse = null;
        try {
            apiResponse = pullClubService.withdrawApply(request, req);
        } catch (Exception e) {
            redisTemplate.delteKey(redisKey);
            logger.warn(e.getMessage());
            throw new BizException(e.getMessage());
        }
        redisTemplate.delteKey(redisKey);
        return apiResponse;
    }


    /**
     * 渠道商进入经销商页面
     *
     * @param reqSellBusiness
     * @return
     */
    @RequestMapping(value = "sellBusinessPageData", method = RequestMethod.POST)
    public APIResponse<Map<String, Object>> sellBusinessPageData(@RequestBody ReqSellBusiness reqSellBusiness) {
        logger.warn("--sellBusinessPageData--" + JSON.toJSONString(reqSellBusiness));
        Map<String, String> exParam = volidateDate(reqSellBusiness.getChannelCode());
        reqSellBusiness.setChannelCode(exParam.get("code"));
        return pullClubOneService.sellBusinessPageData(reqSellBusiness);
    }

    /**
     * 渠道商更改经销商比例
     *
     * @param reqSellBusinessRate
     * @return
     */
    @RequestMapping(value = "setSellBusinessRate", method = RequestMethod.POST)
    public APIResponse setSellBusinessRate(@RequestBody ReqSellBusinessRate reqSellBusinessRate) {
        logger.warn("--setSellBusinessRate--" + JSON.toJSONString(reqSellBusinessRate));
        Map<String, String> exParam = volidateDate(reqSellBusinessRate.getChannelCode());
        reqSellBusinessRate.setChannelCode(exParam.get("code"));
        return pullClubOneService.setSellBusinessRate(reqSellBusinessRate);
    }

    /**
     * 拉新用户详情页面
     *
     * @param reqNewUserDetail
     * @return
     */
    @RequestMapping(value = "getNewUserMessageDetail", method = RequestMethod.POST)
    public APIResponse getNewUserMessageDetail(@RequestBody ReqNewUserDetail reqNewUserDetail) {
        logger.warn("--getNewUserMessageDetail--" + JSON.toJSONString(reqNewUserDetail));
        Map<String, String> exParam = volidateDate(reqNewUserDetail.getCode());
        reqNewUserDetail.setCode(exParam.get("code"));
        return pullClubOneService.getNewUserMessageDetail(reqNewUserDetail);
    }

    /**
     * 验证加密数据
     *
     * @param code
     * @return
     */
    private Map<String, String> volidateDate(String code) {
        Map<String, String> exParam = pullClubSupportService.getDecryptCode(code);
        if (!exParam.containsKey("type") || !exParam.containsKey("code")) {
            throw new BizException(ApiResponseEnum.PARAMETER_INVALID);
        }
        return exParam;
    }

}
